/**
 *
 * http配置
 *
 */

import store from "@/store/";
import router from "@/router/router";
// 引入axios以及element ui中的loading和message组件
import axios from "axios";
import NProgress from "nprogress"; // progress bar
import "nprogress/nprogress.css"; // progress bar style
import { getToken } from "@/util/auth";
import { serialize } from "@/util/util";
axios.defaults.timeout = 30000;
//返回其他状态吗
axios.defaults.validateStatus = function(status) {
  return status >= 200 && status <= 500; // 默认的
};
//跨域请求，允许保存cookie
axios.defaults.withCredentials = true;
NProgress.configure({ showSpinner: false }); // NProgress Configuration
//HTTPrequest拦截
axios.interceptors.request.use(
  config => {
    if (config.url.indexOf("huashi") < 0 && config.url.indexOf("http") < 0) {
      config.url = `/api${config.url}`;
    }
    NProgress.start(); // start progress bar
    const token = getToken();

    //    config.headers['Access-Control-Allow-Origin'] = 'http://127.0.0.1:24010'
    if (token && !config.url.includes("https://cli2.avue.top")) {
      config.headers["token"] = token; // 让每个请求携带token-- ['X-Token']为自定义key 请根据实际情况自行修改
    }
    if (config.method === "post" && config.headers.serialize) {
      config.headers["Content-Type"] = "application/x-www-form-urlencoded";
      config.data = serialize(config.data);
    }
    return config;
  },
  error => {
    console.log("err" + error); // for debug
    return Promise.reject(error);
  }
);
//HTTPresponse拦截
axios.interceptors.response.use(
  res => {
    NProgress.done();
    const status = Number(res.status) || 200;
    if ("401".includes(status)) return Promise.reject(res);
    return res;
  },
  error => {
    NProgress.done();

    return Promise.reject(new Error(error));
  }
);

export default axios;
